先寫一個input的小功能
import React, { useState } from 'react'
import './app4.scss';
export default function App3() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
return (
<div>
<input name="email" className="input" value={email} onChange={e => setEmail(e.target.value)} />
<input name="password" type="password" className="input" value={password} onChange={e => setPassword(e.target.value)} />
<p>{email}</p>
<p>{password}</p>
</div>
);
}
帳號密碼一起列出來
自訂Hooks
import React, {useState} from 'react'
import './app4.scss';
const useForm = (inval) => {
const [values, setValues] = useState(inval);
return[values,(e)=>{
setValues({
...values,
[e.target.name]:e.target.value
})
}]
}
export default function App3() {
const [val, setVal] = useForm({email:'',password:''});
return (
<div>
<input name="email" className="input" value={val.email} onChange={setVal} />
<input name="password" type="password" className="input" value={val.password} onChange={setVal} />
<p>{val.email}</p>
<p>{val.password}</p>
</div>
);
}
這邊自訂一個hooks叫useForm
你也可以把useForm拉出去,新創一個檔案叫
XXX.js
import { useState } from 'react'
export const useForm = (inval) => {
const [values, setValues] = useState(inval);
return[values,(e)=>{
setValues({
...values,
[e.target.name]:e.target.value
})
}]
}
app.js
import React, {useState} from 'react'
import { useForm } from './XXX'
import './app4.scss';
export default function App3() {
const [val, setVal] = useForm({email:'',password:''});
return (
<div>
<input name="email" className="input" value={val.email} onChange={setVal} />
<input name="password" type="password" className="input" value={val.password} onChange={setVal} />
<p>{val.email}</p>
<p>{val.password}</p>
</div>
);
}
這樣這個自訂的Hooks就可以被其他元件使用了